const mongoose = require('mongoose')
const mongoosePaginate = require('mongoose-paginate')
const uiqueVlidator = require('mongoose-unique-validator')
const iparea = require('./iparea')
const schema = new mongoose.Schema({

  ip: {
    type: String,
  },
  area: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'iparea',
     required: [true, '区域必填']
  },
  vlan: {
    type: Number,
  },
  type: {
    type: String,
    required: [true, '类型必填']
  },
  name: {
    type: String,
    unique: true,
  },
  yanmaObj:
    {
      s: {type: String,},
      n: {type: Number,},
    },
  ips: [{
    ip: {type: String,},
    name: {type: String,},
    use: {type: Boolean,default: false,},
    arp: {mac:{type:String},time:{type: Date}},
    oldarp: {mac:{type:String},time:{type: Date}},
  }],
  wangluoip: {
    type: String,
    unique: true,
  },
  guangboip: {
    type: String,
  },
  ipcountinfo: {
    count: {type: Number,},
    startIP: {type: String,},
    endIP: {type: String,},

  },
  beizhu: {
    type: String,
  },
  snmpInfo:{
    ip: {type: String,},
    port: {type: Number,},
    redKey: {type: String,},
    timeSan: {type: Boolean},
  }
}, {
  timestamps: {createdAt: 'createdAt', updatedAt: 'updateAt'}
});


// 自动增加版本号
/* Mongoose 仅在您使用时更新版本密钥save()。如果您使用update()，findOneAndUpdate()等等，Mongoose将不会 更新版本密钥。
作为解决方法，您可以使用以下中间件。参考 https://mongoosejs.com/docs/guide.html#versionKey */

schema.pre('findOneAndUpdate', function () {
  const update = this.getUpdate();
  if (update.__v != null) {
    delete update.__v;
  }
  const keys = ['$set', '$setOnInsert'];
  Object.keys(keys).forEach((key) => {
    if (update[key] != null && update[key].__v != null) {
      delete update[key].__v;
      if (Object.keys(update[key]).length === 0) {
        delete update[key];
      }
    }
  });
  update.$inc = update.$inc || {};
  update.$inc.__v = 1;
});

schema.plugin(mongoosePaginate);
schema.plugin(uiqueVlidator);

module.exports = mongoose.model('iptable', schema)
